<template>
  <CommonLayout>
    <template #header>
      <div class="header-container">
        <div class="system-title">慢病报销管理信息系统</div>
        
        <el-dropdown trigger="click" @command="handleCommand">
          <span class="avatar-wrapper">
            <el-avatar 
              :size="40" 
              :src="avatarUrl"
            />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon><User /></el-icon>
                <span>个人中心</span>
              </el-dropdown-item>
              <el-dropdown-item command="settings">
                <el-icon><Setting /></el-icon>
                <span>账号设置</span>
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon><SwitchButton /></el-icon>
                <span>退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </template>
    <template #main>
      <router-view />
    </template>
  </CommonLayout>
</template>

<script setup>
import CommonLayout from './CommonLayout.vue'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { 
  User,
  Setting,
  SwitchButton
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../utils/request'

const router = useRouter()
const avatarUrl = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')

const handleCommand = async (command) => {
  switch(command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm(
          '确定要退出登录吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await logout()
        ElMessage.success('退出成功')
        router.push('/')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('退出失败')
        }
      }
      break
  }
}

const logout = async () => {
  try {
    // 调用退出登录的 API
    await request.post('/auth/logout')

    // 清除本地存储
    localStorage.removeItem('token')
    sessionStorage.removeItem('userInfo')

  } catch (error) {
    console.error('退出登录失败:', error)
    throw error
  }
}
</script>

<style scoped>
/* 原有样式保持不变 */
.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  width: 100%;
  padding: 0 20px;
}

.system-title {
  font-size: 18px;
  font-weight: 500;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
  height: 100%;
  padding: 0 10px;
}
</style>